package leetcode.code1171;


import leetcode.helper.tree.ListNode;

public class Solution {
	public ListNode removeZeroSumSublists(ListNode head) {
		ListNode L = null;
		int sum = 0;
		while (head != null) {
			if (head.val == 0) {
				head = head.next;
				continue;
			}
			if (L == null) {
				L = head;
				sum += head.val;
				head = head.next;
				L.next = null;
			} else {
				int rest = sum;
				ListNode R = L;
				while (R.next != null && rest != -head.val && rest - R.val != -head.val) {
					rest -= R.val;
					R = R.next;
				}
				if (rest == -head.val) {
					L = null;
					sum = 0;
					head = head.next;
				} else if (rest - R.val == -head.val) {
					R.next = null;
					sum += head.val;
					head = head.next;
				} else {
					R.next = head;
					sum += head.val;
					head = head.next;
					R.next.next = null;
				}
			}
		}
		return L;
	}
}
